<template>
  <div ref="scroll" id="scroll-page" style="overflow: hidden">
    <slot></slot>
    <div v-if="isShowBottomTip" class="my-bottom-tip"><span>~我是有底线的~</span></div>
    <div v-if="loading"
      style="height: 40px;margin-top: 10px;z-index: 1"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(245,245,245)"
      class="my-loading"
    ></div>
  </div>
</template>

<script>
export default {
  props: {
    loading: Boolean,
    noData: Boolean,
    offset: Number
  },
  data () {
    return {
      scrollAction: {
        x: 'undefined',
        y: 'undefined'
      }
    }
  },
  computed: {
    isShowBottomTip () {
      if (this.loading || !this.noData) {
        return false
      } else {
        return true
      }
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll, false)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll (e) {
      if (!this.noData) {
        let curHeight = document.documentElement.scrollTop || document.body.scrollTop
        if ((curHeight + window.innerHeight >= this.$refs.scroll.offsetHeight + this.offset) && this.isDownDirection()) {
          if (!this.loading) {
            this.$emit('load')
          }
        }
      }
    },
    isDownDirection () {
      if (typeof this.scrollAction.x === 'undefined') {
        this.scrollAction.x = window.pageXOffset
        this.scrollAction.y = window.pageYOffset
      }
      var diffX = this.scrollAction.x - window.pageXOffset
      var diffY = this.scrollAction.y - window.pageYOffset

      this.scrollAction.x = window.pageXOffset
      this.scrollAction.y = window.pageYOffset

      if (diffX < 0) {
        // Scroll right
      } else if (diffX > 0) {
        // Scroll left
      } else if (diffY < 0) {
        // Scroll down
        return true
      } else if (diffY > 0) {
        // Scroll up
      } else {
        // First scroll event
      }
      return false
    }
  }
}
</script>

<style>
.my-bottom-tip{
  text-align: center;
  margin-bottom:10px;
  line-height: 20px;
  font-size: 13px;
  color: #969696
}
.my-loading{
  line-height: 15px;
}
</style>
